package com.threaddemo5;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
import java.util.stream.IntStream;

public class ForkJoinRecurisiveTask {
    //最大计算数
    private static final int MAX_THRESHOLD = 5;

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //创建ForkJoinPool
        ForkJoinPool pool = new ForkJoinPool();
        //异步提交RecursiveTask任务
        ForkJoinTask<Integer> forkJoinTask = pool.submit(new CalculatedRecurisiveTask(0,1000));
        //根据返回类型获取返回值
        Integer result = forkJoinTask.get();
        System.out.println("结果为："+result);
    }

    private static class CalculatedRecurisiveTask extends RecursiveTask<Integer>{
        private int start;
        private int end;
        public CalculatedRecurisiveTask(int start, int end) {
            this.start = start;
            this.end = end;
        }
        @Override
        protected Integer compute() {
            //判断计算范围，如果小于等于5，那么一个线程计算就够了，否则进行分割
            if ((end-start)<=5) {
                int sum = 0;

                for (long i = start; i <= end; i++) {
                    sum += i;
                }

                return sum;
            }else {
                //任务分割
                int middle = (end+start)/2;
                CalculatedRecurisiveTask left = new CalculatedRecurisiveTask(start,middle);
                CalculatedRecurisiveTask right = new CalculatedRecurisiveTask(middle+1,end);
                //执行
                left.fork();
                right.fork();
                //等待返回结果
                return left.join()+right.join();
            }
        }
    }
}

